import { useEffect, useState } from "react";
import { createSchemaFormRender } from "@/components/schema-form-render";
import { getPageMeta } from "@/services/request/meta";
import { MetaSorted } from "schema-form";
import {
  formatArrayCollap,
  formatForArrayTable,
  initialSchemaNoraml,
  initialSchemaSearch,
} from "@/components/schema-form-render/utils";
import { useCacheData } from "./with-list/use-events";
/**
 * 高阶新增页面，事件注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerEvent = (target: any, events: any, params: any) => {
  const { setLoading = () => {}, match } = params;
  if (events) {
    Object.keys(events).forEach((hookName) => {
      target[hookName] = async () => {
        if (events && events[hookName]) {
          setLoading(true);
          try {
            const res: any = await events[hookName](params);
            if (res?.success) {
              setLoading(false);
            }
            setLoading(false);
          } catch (err) {
            setLoading(false);
          }
        }
      };
    });
  }
};

/**
 * 高阶列表页面，列表按钮事件注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerListTableEvent = (
  target: any,
  events: any,
  params: any
) => {
  const { setLoading = () => {}, match } = params;
  Object.keys(events).forEach((hookName) => {
    let old: any = null;
    if (target[hookName]) {
      old = target[hookName];
    }
    target[hookName] = async (id: string, row: any, index: number) => {
      if (events && events[hookName]) {
        setLoading(true);
        const [searchCache] = useCacheData(match);
        params.searchCache = searchCache;
        const res: any = await events[hookName](id, row, params, index);
        if (res?.success) {
          params.callback && params.callback(true);
          setLoading(false);
        }
        old && old(id, row);
        setLoading(false);
      }
    };
  });
};

/**
 * 高阶列表页面，普通按钮注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerListButtonEvent = (
  target: any,
  events: any,
  params: any
) => {
  const { setLoading = () => {}, match } = params;
  Object.keys(events).forEach((hookName) => {
    let old: any = null;
    if (target[hookName]) {
      old = target[hookName];
    }
    target[hookName] = async () => {
      if (events && events[hookName]) {
        setLoading(true);
        const [searchCache] = useCacheData(match);
        params.searchCache = searchCache;
        const res: any = await events[hookName](params);
        console.log("res", res);
        setLoading(false);
        if (res?.success) {
        }
        old && old();
      }
    };
  });
};

/**
 *
 * @param filedConfig 字段配置
 * @param formConfigs form 配置
 * @param initForm 初始化 form 方法
 * @returns
 */
export const useScemaRender = (
  filedConfig: any,
  formConfigs: any,
  initForm?: any,
  needCache = true,
  ali: any[] = []
) => {
  const [configs, setCongis] = useState<any>({
    form: null,
    Render: null,
  });
  useEffect(() => {
    const res = createSchemaFormRender(filedConfig, formConfigs, {
      needCache,
    });
    setCongis(res);
    if (initForm && typeof initForm === "function") {
      initForm().then((res2: any) => {
        // 处理 Name
        const suffix = "Name";
        const result = res2.result;
        const keys: any[] = Object.keys(result);
        keys.forEach((k: string) => {
          if (result[k + suffix]) {
            result[k] = result[k + suffix];
          }
        });
        res.form.setInitialValues(result);
      });
    }
  }, ali);
  return {
    form: configs.form,
    SchemaFormRender: configs.Render,
  };
};
/**
 *
 * @param pageCode
 * @param type
 * @param eventMap
 * @returns
 */
export const useMetaInit = (
  pageCode: string,
  type: "SEARCH" | "DETAIL" | "NORMAL" = "SEARCH",
  eventMap: any = {}
): [MetaSorted, any] => {
  const [configs, setConfigs] = useState<MetaSorted>({});
  useEffect(() => {
    getPageMeta(pageCode).then(async (res: any) => {
      if (res.success) {
        const sss: any =
          type === "SEARCH"
            ? initialSchemaSearch(res.result, "", false)
            : initialSchemaNoraml(res.result, false, type, eventMap);
        await formatForArrayTable(sss.ArrayTableList, sss.schema, type);
        await formatArrayCollap(sss.ArrayColList, sss.schema, type);
        setConfigs(sss);
      }
    });
  }, []);
  return [configs, setConfigs];
};

/**
 *
 * @param object
 * @returns string
 */
export const getExportParams = (object: any) => {
  if (object) {
    const prarms: string[] = [];
    Object.keys(object).forEach((key) => {
      prarms.push(`${key}=${object[key]}`);
    });
    return prarms.join("&");
  }
  return "";
};
